<template>
  <el-upload class="avatar-uploader" :action="UploadUrl" :headers="{
    Authorization
  }" name="multipartFile" :show-file-list="false" :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload"
    accept=".png, .jpg">
    <el-image v-if="preview_url" :src="preview_url" class="avatar" :class="{ 'avatar2': mini }">
    </el-image>
    <el-icon v-else class="avatar-uploader-icon" :class="{ 'avatar-uploader-icon2': mini }">
      <Plus />
    </el-icon>
  </el-upload>
</template>

<script  setup>
import { ref, computed, watch } from 'vue'
import { Plus } from '@element-plus/icons-vue'
import { ElMessage } from "element-plus"
const Authorization = localStorage.getItem('token') ? localStorage.getItem('token') : "";
// const baseURL = import.meta.env.VITE_MODE != 'dev' ? import.meta.env.VITE_API_HOST : '/api'
const UploadUrl = "/api/uploadFile"
const props = defineProps({
  modelValue: String,
  size: Number,
  mini: Boolean
})

const emit = defineEmits(['update:modelValue'])
const imageUrl = ref('')
const preview_url = computed(() => {
  let url = null;
  if (imageUrl.value && imageUrl.value.indexOf('/res') == 0) {
    url = imageUrl.value
  }
  if (props.modelValue && props.modelValue.indexOf('/res') == 0) {
    url = import.meta.env.VITE_API_HOST + props.modelValue
  }
  return url;
})
const handleAvatarSuccess = (
  response,
  uploadFile
) => {
  let res = response
  if (!res.success) {
    ElMessage.error(res.message)
  } else {
    emit('update:modelValue', res.entity.fileUrl)
  }
  //   imageUrl.value = URL.createObjectURL(uploadFile.raw)
}

const beforeAvatarUpload = (rawFile) => {
  const type_arr = ["image/jpeg", "image/png"];
  if (!type_arr.includes(rawFile.type)) {
    ElMessage.error('文件格式不正确!')
    return false
  }
  const size = props.size ?? 5;
  if (rawFile.size / 1024 / 1024 > size) {
    ElMessage.error('上传大小不得超过 ' + size + 'M')
    return false
  }
  return true
}
</script>

<style lang="scss" scoped>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}

.avatar-uploader .avatar2 {
  width: 120px;
  height: 120px;
  display: block;
}

.avatar-uploader :deep(.el-upload) {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader :deep(.el-upload:hover) {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}

.el-icon.avatar-uploader-icon2 {
  font-size: 28px;
  color: #8c939d;
  width: 120px;
  height: 120px;
  text-align: center;
}
</style>